package com.local.web.service.impl;

import com.local.cart.feign.CartServiceFeign;
import com.local.cart.pojo.ShoppingCart;
import com.local.common.constants.BusinessException;
import com.local.common.constants.ExceptionCodeEnum;
import com.local.common.util.ResultUtil;
import com.local.web.constants.WebConstants;
import com.local.web.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Objects;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private CartServiceFeign cartServiceFeign;

    /**
     * 查询用户的购物车列表
     * @param userId
     * @return
     */
    @Override
    public List<ShoppingCart> getListByUserId(HttpSession session, Integer userId) {
        ResultUtil<List<ShoppingCart>> listResult = cartServiceFeign.getListByUserId(userId);
        if (Objects.isNull(listResult)) {
            throw new BusinessException(ExceptionCodeEnum.BUSINESS_EXCEPTION.getCode(), ExceptionCodeEnum.BUSINESS_EXCEPTION.getMessage());
        }
        if (listResult.getCode() != 200) {
            throw new BusinessException(listResult.getCode(), listResult.getMessage());
        }
        List<ShoppingCart> list = listResult.getData();
        return list;
    }


    /**
     * 加入购物车
     * @param cart
     * @return
     */
    @Override
    public ResultUtil addToCart(HttpSession session, ShoppingCart cart) {
        ResultUtil<ShoppingCart> addResult = cartServiceFeign.add(cart);
        if (Objects.isNull(addResult)) {
            throw new BusinessException(ExceptionCodeEnum.BUSINESS_EXCEPTION.getCode(), ExceptionCodeEnum.BUSINESS_EXCEPTION.getMessage());
        }
        return addResult;
    }

    @Override
    public ResultUtil deleteByCartItemId(HttpSession session, Integer cartItemId) {
        ResultUtil deleteResult = cartServiceFeign.delete(cartItemId);
        if (Objects.isNull(deleteResult)) {
            throw new BusinessException(ExceptionCodeEnum.BUSINESS_EXCEPTION.getCode(), ExceptionCodeEnum.BUSINESS_EXCEPTION.getMessage());
        }
        return deleteResult;
    }

    @Override
    public ResultUtil updateGoodsCount(HttpSession session, ShoppingCart shoppingCart) {
        ResultUtil updateResult = cartServiceFeign.updateGoodsCount(shoppingCart);
        if (Objects.isNull(updateResult)) {
            throw new BusinessException(ExceptionCodeEnum.BUSINESS_EXCEPTION.getCode(), ExceptionCodeEnum.BUSINESS_EXCEPTION.getMessage());
        }
        return updateResult;
    }
}
